
import store from '@/store'
import {
	request
} from '@/http/request.js';
module.exports = {
	deep_copy: (obj) => {
		return JSON.parse(JSON.stringify(obj))
	},
	send_message:(message,channel='chat') => {

		return new Promise((resolve,reject) => {
			getApp().goeasy.pubsub.publish({
				channel,
				message,
				onSuccess: () =>  {
					resolve()
				},
				onFailed: (error) =>  {
					reject('消息发送失败',error)
				}
			})
		})
	},
	save_game : async (ismessage = true) => {
		
		return new Promise( async (resolve,reject) => {
			
			let player_data = JSON.parse(JSON.stringify(store.state.mod_player.player))
			delete player_data['_id']
			
			await request({
				name : 'player',
				method : 'save_player',
				player_data
			})

			if(ismessage){
				uni.$emit('game-info',{
					content : `<span style="color:var(--color-red2)">[系统]</span> <span style="color:var(--color-green)">游戏数据保存成功</span>`
				})
			}
			
			resolve()
			
		})

		
		

	},
	rnd: (Min, Max) => {
		var Range = Max - Min;
		var Rand = Math.random();
		var num = Min + Math.round(Rand * Range);
		return num;
	},
	create_uid :() => {
	    return (Math.random() * 10000000).toString(16).substr(0, 4) + (new Date()).getTime() + Math.random().toString().substr(2, 5);
	},
	
	/*
		从数组arr中随机取n个不重复的元素
	*/
	getRandomElements : (arr,n) => {
		// 创建一个新的数组，防止修改原数组
		const copyArr = arr.slice();
		// 存储随机选择的元素
		const result = [];
		// 当数组中还有元素时继续循环
		while (result.length < n && copyArr.length > 0) {
			// 生成一个随机索引
			const randomIndex = Math.floor(Math.random() * copyArr.length);
			// 将选择的元素添加到结果数组中
			result.push(copyArr.splice(randomIndex, 1)[0]);
		}
		return result;
	},
	
	/*
		各种概率
	*/
	probability(prizes) {
		// 计算概率总和
		const totalProbability = prizes.reduce((acc, cur) => acc + cur.PR, 0);
	  
		// 生成随机数
		const randomNum = Math.random();
	  
		// 遍历奖品数组，确定抽到的奖品
		let currentProbability = 0;
		for (let i = 0; i < prizes.length; i++) {
		  const prize = prizes[i];
		  currentProbability += prize.PR / totalProbability;
		  if (randomNum <= currentProbability) {
			return prize;
		  }
		}
	  
		// 如果没有中奖，则返回 null 或者一个默认奖品
		return null;
	},
}